<?php
namespace app\admin\controller;

use think\exception\ValidateException;
use app\model\AdminMenu;

class AdminmenuController extends Base
{

	function index()
	{
		$keyword = input('post.keyword', '', 'serach_in');

		$query = AdminMenu::field('id,title,type,component_path,status,path,sort,pid');

		if (!empty($keyword)) {
			$query->where('title', 'like', '%' . $keyword . '%');
		}

		$list = $query->order('sort asc')->select()->toArray();
		$data['data'] = _generateListTree($list, 0, ['id', 'pid']);
		
		return $this->json($data);
	}

	function updateExt()
	{
		$postField = 'id,status,sort';
		$data = $this->request->only(explode(',', $postField), 'post', null);
		if (!$data['id']) throw new ValidateException('参数错误');
		AdminMenu::update($data);

		return $this->json(['msg' => '操作成功']);
	}

	public function add()
	{
		$postField = 'title,pid,type,component_path,status,path,icon,sort';
		$data = $this->request->only(explode(',', $postField), 'post', null);
		$data['pid']= (int)$data['pid'];
		$this->validate($data, \app\validate\AdminMenu::class);
		
		try {
			$res = AdminMenu::create($data);
			if ($res->id && empty($data['sort'])) {
				AdminMenu::update(['sort' => $res->id, 'id' => $res->id]);
			}
		} catch (\Exception $e) {
			throw new ValidateException($e->getMessage());
		}

		return $this->json(['msg' => '添加成功', 'data' => $res->id]);
	}

	public function update()
	{
		$id = $this->request->post('id');
		if (empty($id)) {
			return $this->add();
		} else {
			$postField = 'id,title,pid,type,component_path,status,path,icon,sort';
			$data = $this->request->only(explode(',', $postField), 'post', null);
			$data['pid']= (int)$data['pid'];
			$this->validate($data, \app\validate\AdminMenu::class);
			
			try {
				AdminMenu::update($data);
			} catch (\Exception $e) {
				throw new ValidateException($e->getMessage());
			}
			return $this->json(['msg' => '修改成功']);
		}
	}

	function getUpdateInfo()
	{
		$id =  $this->request->post('id', '', 'serach_in');
		if (!$id) throw new ValidateException('参数错误');
		$field = 'id,title,pid,type,component_path,status,path,icon,sort';
		$res = AdminMenu::field($field)->find($id);
		return $this->json(['data' => $res]);
	}

	function delete()
	{
		$idx =  $this->request->post('id', '', 'serach_in');
		if (!$idx) throw new ValidateException('参数错误');
		AdminMenu::destroy(['id' => explode(',', $idx)], true);
		return $this->json(['msg' => '操作成功']);
	}

	function getField()
	{
		$data['pids'] =_generateSelectTree(AdminMenu::getpidarray());
		return $this->json(['data' => $data]);
	}
}